/*
 * @Author: Huangdong
 * @Date: 2022-03-28 15:21:05
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @LastEditTime: 2025-11-21 15:16:07
 * @FilePath: \01.latest-short-insure\src\utils\index.js
 * @Description:
 *
 *
 */
import { Toast } from "vant";
/**
 * 获取运行环境
 * @returns
 */
export const openInWebview = () => {
  if (window.minsheng || window.isUniapp) {
    return "ms";
  }
  if (getDataFromUrl("origin") == "ms") {
    return "ms";
  }
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    // 微信浏览器判断
    return "wx";
  } else {
    // 测试APP专用

    if (ua.match(/Android/i) != null) {
      return ua.match(/browser/i) == null ? "ms" : "pc";
    } else if (ua.match(/iPhone/i) != null) {
      return ua.match(/safari/i) == null ? "ms" : "pc";
    } else {
      return ua.match(/macintosh/i) == null && ua.match(/windows/i) == null
        ? "ms"
        : "pc";
    }
  }
};

/**
 * 从地址栏里获取数据
 * @param {*} name 参数
 */
export const getDataFromUrl = (name) => {
  var url = window.location.search;
  // 正则筛选地址栏
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  // 匹配目标参数
  var result = url.substr(1).match(reg);
  //返回参数值
  return result ? decodeURIComponent(result[2]) : null;
};

/**
 * 分享路由改成指定的路径
 * 测试: /app_h5/latestshort/
 */
export const appShare = ({
  url,
  title,
  desc,
  icon = "/app_h5/insurance/static/image/logo80.png",
}) => {
  let shareUrl = "";
  if (url.indexOf("http") === 0) {
    shareUrl = url;
  } else {
    if (
      window.location.origin.indexOf("wxou") !== -1 ||
      process.env.VUE_APP_PRODFLAG == "localpro"
    ) {
      shareUrl = `/app_h5/latestshort/${url}`;
    } else if (
      window.location.origin.indexOf("wxsc") !== -1 ||
      process.env.VUE_APP_PRODFLAG == "localdev"
    ) {
      shareUrl = `http://wxsc.mschn.cn/app_h5/testinsurance/latestshort/${url}`;
    } else {
      shareUrl = `${window.location.origin + window.location.pathname}${url}`;
    }
  }

  let obj = urlToJson(shareUrl);
  var timestamp = new Date().getTime();
  if (obj && obj.orderNum) {
    // 保存分享时间戳,地址拼接时间戳 替换url；
    shareUrl = addUrlPara("timestamp", timestamp, shareUrl);
  }
  console.log(shareUrl, title, desc, icon);
  if (isUniapp) {
    uni.postMessage({
      data: {
        action: "share",
        data: {
          url: shareUrl, //（type 为 0 时必传）
          title: title,
          desc: desc, //（type 为 1 时必传）
          icon: icon, //
          type: "0", //0图文 1纯文字 2纯图片 3音乐 4视频 5小程序
        },
      },
    });
  } else {
    if (window.minsheng) {
      window.minsheng.share(url, title, desc, icon);
    } else {
      try {
        tianbai.share(url + "@" + title + "@" + desc + "@" + icon);
      } catch (error) {
        // Toast('请在APP中打开');
        copyTxt(url, () => {
          Toast("已复制链接");
        });
      }
    }
  }
};

export const copyTxt = (t, callBack) => {
  if (!navigator.clipboard) {
    var ele = document.createElement("input");
    ele.value = t;
    document.body.appendChild(ele);
    ele.select();
    document.execCommand("copy");
    document.body.removeChild(ele);
    if (document.execCommand("copy")) {
      callBack();
    } else {
      console.log("复制失败！");
    }
  } else {
    navigator.clipboard
      .writeText(t)
      .then(function (res) {
        callBack();
      })
      .catch(function () {
        console.log("复制失败！");
      });
  }
};

// 分享到微信和朋友圈
export const saveFile = (dataURL, type) => {
  if (isUniapp) {
    uni.postMessage({
      data: {
        action: "share",
        data: {
          // url: test, //（type 为 0 时必传）
          // title: productName,
          // desc: description, //（type 为 1 时必传）
          icon: dataURL, //
          shareType: type == 1 ? "WXSenceTimeline" : "WXSceneSession", //'1'朋友圈 2微信好友
          type: "2", //0图文 1纯文字 2纯图片 3音乐 4视频 5小程序
        },
      },
    });
  } else {
    Toast("请在APP中打开");
  }
};

// 将url参数转为对象
export const urlToJson = (url = window.location.href) => {
  // 箭头函数默认传值为当前页面url
  let obj = {},
    index = url.indexOf("?"), // 看url有没有参数
    params = url.substr(index + 1); // 截取url参数部分 id = 1 & type = 2
  if (index != -1) {
    // 有参数时
    let parr = params.split("&"); // 将参数分割成数组 ["id = 1 ", " type = 2"]
    for (let i of parr) {
      // 遍历数组
      let arr = i.split("="); // 1） i id = 1   arr = [id, 1]  2）i type = 2  arr = [type, 2]
      obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1   obj[arr[0]] = type, obj.type = 2
    }
  }
  return obj;
};

// url中加入参数，暂时正则表达是带参数替换尚有问题
export const addUrlPara = (name, value, url) => {
  var currentUrl = url.split("#")[0];
  if (/\?/g.test(currentUrl)) {
    if (/name=[-\w]{4,25}/g.test(currentUrl)) {
      currentUrl = currentUrl.replace(/name=[-\w]{4,25}/g, name + "=" + value);
    } else {
      currentUrl += "&" + name + "=" + value;
    }
  } else {
    currentUrl += "?" + name + "=" + value;
  }
  if (url.split("#")[1]) {
    return currentUrl + "#" + url.split("#")[1];
  } else {
    return currentUrl;
  }
};

/**查看订单详情 */
export const appOrderDetail = (orderNum, workNum) => {
  if (isUniapp) {
    uni.redirectTo({
      url: "/pages/user/order/detail?orderNum=" + orderNum,
    });
  } else {
    let origin = "http://wxsc.mschn.cn";
    if (window.location.origin.indexOf("wxou") !== -1) {
      origin = window.location.origin;
    }
    window.location.href = `${origin}/app/pages/user/order/detail?jump=1&orderNum=${orderNum}&workNum=${workNum}`;
  }
};

export const money = function (value) {
  // 价格的限制规则，只能输入小数点后两位
  value = value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  value = value.replace(/^\./g, ""); //验证第一个字符是数字而不是字符
  value = value.replace(/\.{2,}/g, "."); //只保留第一个.清除多余的
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
  return value;
};